import axios from 'axios'
import Vue from 'vue'
// 环境value
let _isDev = process.env.NODE_ENV === 'development'
    // webpack require.context 转为对象包装函数 
export const webpackRequire2obj = (r, exinclude) => {
        let contents = {}
        const paths = r.keys().filter((p, i) => {
            return exinclude.indexOf(p) == -1
        });
        for (let p of paths) {
            let fn = r(p).default ? r(p).default : r(p)
            let k = p.match(/(\w+-?\w+).js$/)[1]
            contents[k] = fn
        }
        return contents
    }
    /**
     * 去中心化
     * @param {上下文} requireContext 
     * @param {排除文件} exinclude 
     */
export const deCentralization = (
    requireContext,
    fn = (a, b) => ({
        ...a,
        ...b
    })
) => {
    console.log(requireContext.keys())
    const sourceMap = (r => {
        return requireContext.keys().map(k => {
            return r(k).default
        })
    })(requireContext)
    console.log(sourceMap)
    return sourceMap.reduce(fn)
}


export const lazyVue = (name, index = false) => () =>
    import (`@/views/${name}${index ? '/index' : ''}.vue`)
    /**
     * 开发输出log
     * @param {消息} msg 
     */
export const log = (msg) => {
    if (_isDev && console && console.log) {
        console.log(msg)
    }
}

/**
 * 获取上传token
 */
// export const getUploadToken = () => {
//     return new Promise((resolve, reject) => {
//         if (Cookies('Upload_Token')) {
//             resolve(Cookies('Upload_Token'))
//         } else {
//             apis.userUploadToken()
//                 .then(d => {
//                     Cookies('Upload_Token', d.upload_token, {
//                         expires: 3600
//                     })
//                     resolve(d.upload_token)
//                 })
//         }
//     })
// }

/**
 * 构造fromData数据
 * @param {文件} f 
 * @param {资源远程目录} key 
 * @param {formData文件名} name 
 */
export const appendFormData = (f, name, key = '') => {
        let formData = new window.FormData()
        formData.append(name, f)
        return new Promise((resolve, reject) => {
            getUploadToken()
                .then(token => {
                    formData.append('token', token)
                    resolve(formData)
                })
        })
    }
    /**
     * 简易上传（头像上传）
     * @param {文件} f 
     * @param {host} host 
     * @param {资源远程目录} key 
     */
export const uploadFile = (f, host, key) => {
    return new Promise((resolve, reject) => {
        appendFormData(f, 'file', key)
            .then(fd => {
                axios.post(host, fd, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    }).then(d => {
                        resolve(d.data)
                    })
                    .catch(res => {
                        let _response = res.response
                        Vue.$vux.toast.show({
                            text: _response.data && _response.data.error ? _response.data.error : '上传错误',
                            type: 'warn'
                        })
                        Cookies('Upload_Token', undefined)
                        reject(_response)
                    })
            })
    })
}

/**
 * 判断空数组或对象
 * @param value
 */
export const isEmpty = (value) => {
    return Object.keys(value).length === 0;
}

/**
 * 截取小数点位数
 * @param {数值} value 
 * @param {小数点位数} len 
 */
export const toFixed = (value, len = 2) => {
    return value ? parseFloat(value).toFixed(len) : 0
}

/**
 * 获取style样式
 */
export const getStyle = (element, attr) => {
    let target
        // scrollTop 获取方式不同，不属于style，而且只有document.body才能用
    if (attr === 'scrollTop') {
        target = element.scrollTop
    } else if (element.currentStyle) {
        target = element.currentStyle[attr]
    } else {
        target = document.defaultView.getComputedStyle(element, null)[attr]
    }
    return target
}



/**
 * 数组删除指定元素
 */
export function removeByValue(arr, val) {  
    for (var i = 0; i < arr.length; i++) {    
        if (arr[i] == val) {  
            arr.splice(i, 1);      
            break;    
        }  
    }
}